package com.penngo.gui.dfdiff.view;

import com.penngo.gui.dfdiff.utils.ImgUtil;

import com.penngo.gui.dfdiff.utils.LogUtils;
import org.jdesktop.swingx.table.ColumnFactory;
import org.jdesktop.swingx.table.TableColumnExt;

import javax.swing.*;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.logging.Logger;

public class FolderTable extends DfTreeTable {
    private Logger log = LogUtils.getLogger(FolderTable.class);
    private SelfExpansionListener expansionListener;
    private SelfFileDiffListener fileDiffListener;
    public enum Type {
        LEFT, RIGHT
    }
    private FolderModel folderModel;
    private Type type;
    private JPopupMenu popupMenu = new JPopupMenu();

    public FolderTable(FolderNode root, Type type) {
        this.type = type;
        this.root = root;

        folderModel = new FolderModel(root, type);

        this.setExpandsSelectedPaths(true);
        createPopupMenu();
        ColumnFactory factory = new ColumnFactory() {
            String[] columnNameKeys = { "名称(N)", "大小(Z)", "修改日期(M)"};

            @Override
            public void configureTableColumn(TableModel model,
                                             TableColumnExt columnExt) {
                super.configureTableColumn(model, columnExt);
                if (columnExt.getModelIndex() < columnNameKeys.length) {
                    columnExt.setTitle(columnNameKeys[columnExt.getModelIndex()]);
                }
            }

        };
        this.setColumnFactory(factory);
        this.setTreeTableModel(folderModel);
        this.addTreeExpansionListener(new TreeExpansionListener() {
            @Override
            public void treeExpanded(TreeExpansionEvent event) {
                expansionListener.treeExpanded(event);
            }

            @Override
            public void treeCollapsed(TreeExpansionEvent event) {
                expansionListener.treeCollapsed(event);
            }
        });
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent event) {
                super.mouseClicked(event);
                if (event.getButton() == MouseEvent.BUTTON3){
                    int row = FolderTable.this.rowAtPoint(event.getPoint());
                    FolderTable.this.setRowSelectionInterval(row, row);
                    popupMenu.show(event.getComponent(), event.getX(), event.getY());
                }
                else if(event.getClickCount() == 2){
                    openDiffFile();
                }
            }
        });
    }

    private void openDiffFile(){
        int row = FolderTable.this.getSelectedRow();
        FolderModel model = (FolderModel) FolderTable.this.getTreeTableModel();
        FolderNode node = (FolderNode) FolderTable.this.getValueAt(row, 0);
        try{
            File file = new File(model.getRootFile(), node.getPath());
            if(file.exists() == true){
                fileDiffListener.action(node.getPath());
            }
            else{
                log.severe("打开文件不存在");
            }
        }
        catch(Exception ex){
            log.warning("=====open error" + ex.getMessage());
        }
    }

    public void setFile(File file, FinishListener listener) {
        folderModel.setFile(file, listener);

    }

    public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {

        Component component = super.prepareRenderer(renderer, row, column);
        int selectedRow = this.getSelectedRow();
        if(row % 2 == 1 && row != selectedRow){
            component.setBackground(new Color(240,240,240));
        }
        Object obj = this.getValueAt(row, 0);

        if(obj instanceof FolderNode){

            FolderNode folderCell = (FolderNode)obj;
            if(folderCell.getLeft() == FolderNode.CheckType.YES &&
                    folderCell.getRight() == FolderNode.CheckType.YES){
                // 不存在
                if(folderCell.getLeftExist() != FolderNode.ExistType.YES ||
                        folderCell.getRightExist() != FolderNode.ExistType.YES){
                    component.setForeground(Color.RED);
                }
                // 不相同
                else if(folderCell.isSame() != true){
                    component.setForeground(Color.MAGENTA);
                }
            }
        }

        return this.applyRenderer(component, this.getComponentAdapter(row, column));
    }
    interface FinishListener{
        void action();
    }
    interface SelfExpansionListener{
        void treeExpanded(TreeExpansionEvent event);
        void treeCollapsed(TreeExpansionEvent event);
    }

    public void addExpansionListener(SelfExpansionListener expansionListener) {
        this.expansionListener = expansionListener;
    }

    interface SelfFileDiffListener{
        void action(String path);
    }
    public void addFileDiffListener(SelfFileDiffListener fileDiffListener) {
        this.fileDiffListener = fileDiffListener;
    }

    private void createPopupMenu() {
        String resourceCommand = "在资源管理器打开";
        String diffCommand = "比较文件差异";
        ImageIcon folderIcon = ImgUtil.getIcon("/images/folder.png");
        folderIcon.setImage(folderIcon.getImage().getScaledInstance(16,16, Image.SCALE_DEFAULT));
        JMenuItem popup1 = new JMenuItem(resourceCommand, folderIcon);
        JMenuItem fileDiff = new JMenuItem(diffCommand, ImgUtil.IMAGE_FILE);
        ActionListener al = e -> {
            String command = e.getActionCommand();
            int row = FolderTable.this.getSelectedRow();
            FolderModel model = (FolderModel) FolderTable.this.getTreeTableModel();
            FolderNode node = (FolderNode) FolderTable.this.getValueAt(row, 0);
            try{
                File file = new File(model.getRootFile(), node.getPath());
                if(file.exists() == true){
                    if(command.equals(resourceCommand)){
                        String os = System.getProperty("os.name");
                        if(os.startsWith("Windows")){
                            // 打开window文件夹
                            Runtime.getRuntime().exec("explorer /select," + file.getAbsolutePath());
                        }
                        else if(os.startsWith("Mac")){
                            // 打开finder文件夹
                            Runtime.getRuntime().exec("open -R " + file.getAbsolutePath());
                        }
                        else{
                            Desktop.getDesktop().open(file.getParentFile());
                        }
                    }
                    else if(command.equals(diffCommand)){
                        fileDiffListener.action(node.getPath());
                        //DFMain.tabbedPane.addTab("文件差异", new FileTabPanel(file));
                    }
                }
                else{
                    log.severe("打开文件不存在");
                }
            }
            catch(Exception ex){
                log.warning("=====open error" + ex.getMessage());
            }
        };
        popup1.addActionListener(al);
        fileDiff.addActionListener(al);
        popupMenu.add(popup1);
        popupMenu.add(fileDiff);
    }


}
